/**
 * 公共js
 * User: jay.zhoujingjie
 * Date: 13-12-19
 * Time: 下午3:30
 * @author jay.zhoujingjie
 */
$(document).ready(function () {
    /**
     * 阻止超链接默认行为
     */
    $("a").on("mousedown", function (event) {
        event.preventDefault();
//		return false;
    });
});

var common = ({
    // 每次查询的页数以及每页行数
    page: 1,
    rows: 10,

    // 模糊查询特殊字符
    specialString: ['_', '%'],

    // 对模糊查询特殊字符进行处理
    replaceString: function (str) {
        for (var i = 0; i < common.specialString.length; i++) {
            var reg = new RegExp('\\' + common.specialString[i], "g");
            var rep = "\\" + common.specialString[i];
            str = str.replace(reg, rep);
        }
        return str;
    },

    //授权类型
    authorizationType: [{
        value: 0,
        text: '开关锁授权'
    }, {
        value: 1,
        text: '初始化授权'
    }, {
        value: 2,
        text: '复位授权'
    }, {
        value: 3,
        text: '更换密钥授权'
    }],

    //授权状态
    authorizationStatus: [{
        value: 1,
        text: "启用"
    }, {
        value: 0,
        text: '停用'
    }, {
        value: 2,
        text: "失效"
    }],

    pageList: [30, 50, 70, 100, 200, 500, 1000, 2000, 5000, 10000],

    tagId: '#choseTags',
    tagList: '#showTags',
    tagListUl: '#showTagsUl',
    tags_dg: '#show_tags_dg',
    deleteTagOperate: "<button onclick='common.deleteTag()'>删除</button>",

    //标签选择界面是否已经初始化
    isInitChooseTag: false,

    //标签输入框id
    tagInputId: null,

    //总标签集合
    totalTags: [],

    //用户已选标签集合
    userTags: [],

    //已存在标签集合
    myTags: [],

    //标签ids
    tagIds: '',

    //======================标签、部门信息====================
    // 标签
    tagQueryUrl: location.path + "tagAction!queryAll.action",
    tagSaveUrl: location.path + 'tagAction!addTag.action',
    reloadTagList: [{"id": ".common_tag_type_search", "is_search": "Y"},
        {"id": ".common_tag_type_other", "is_search": "O"},
        {"id": ".common_tag_type_new", "is_search": "N"}],
    isTag: 1,
    // 部门
    deptQueryUrl: location.path + "deptAction!queryAllDept.action",
    deptSaveUrl: location.path + 'deptAction!addDept.action',
    reloadDeptList: [{"id": ".common_dept_new", "is_search": "N"},
        {"id": ".common_dept_search", "is_search": "Y"},
        {"id": ".common_dept_other", "is_search": "O"}],
    isDept: 2,
    //	角色
    roleQueryUrl: location.path + 'roleAction!getAllRoles.action',
    roleSaveUrl: location.path + 'roleAction!addRole.action',
    reloadRoleList: [{"id": ".common_role_search", "is_search": "Y"},
        {"id": ".common_role_other", "is_search": "O"}],
    isRole: 3,

    //日期格式化
    dateFormatter: function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
    },

    //日期格式化 带时 分 秒
    dateFormatter_Time: function (date) {
        date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var h = date.getHours();
        var M = date.getMinutes();
        var s = date.getSeconds();
        return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) +
            ' ' + (h < 10 ? ('0' + h) : h) + ':' + (M < 10 ? ('0' + M) : M) + ':' +
            (s < 10 ? ('0' + s) : s);
    },

    // 解析日期
    dateParser: function (dateStr) {
        if (!dateStr) {
            return new Date();
        }
        var dateStrs = dateStr.split('-');
        var y = parseInt(dateStrs[0], 10);
        var m = parseInt(dateStrs[1], 10);
        var d = parseInt(dateStrs[2], 10);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
            return new Date(y, m - 1, d);
        } else {
            return new Date();
        }
    },

    // datagrid 格式化时间
    formatter_Time: function (val, row, Index) {
        if (val != null) {
            return common.dateFormatter(new Date(val));
//			var time=new String(val);
//			return time.substr(0,10);
        }
        return "";
    },

    // datagrid 格式化时间  带时分秒的
    formatter_Time_Hour: function (val, row, Index) {
        if (val != null) {
            return common.dateFormatter_Time(new Date(val));
        }
        return "";
    },

    // 格式化部门、标签、角色等
    formatter_allName: function (val, row, Index) {
        if (val != null) {
            var tagValue = "";
            $.each(val, function (index, item) {
                tagValue += item.name + "、";
            });
            tagValue = tagValue.substring(0, tagValue.length - 1);
            return tagValue;
        }
        return "";
    },

    // 格式化授权状态
    formatter_authorization_status: function (val, row, index) {
        switch (val) {
            case '0':
                return "停用";
                break;
            case '1':
                return "启用";
                break;
            case '2':
                return "失效";
                break;
            default:
                return "";
                break;
        }
    },

    // 格式化授权类型
    formatter_authorization_type: function (val, row, index) {
        switch (val) {
            case '0':
                return "开关锁授权";
                break;
            case '1':
                return "初始化授权";
                break;
            case '2' :
                return "复位授权";
                break;
            case '3' :
                return "更换密钥授权";
                break;
            default:
                return "";
                break;
        }
    },


    // dialog 页面水平居中显示
    dialog_center_show: function (param) {
        // dialog 水平宽度
        var dialog_width = $(param).dialog('options').width;
        var dialog_height = $(param).dialog('options').height;
        // 水平居中显示
//		$(param).dialog("move",{top:$(document).scrollTop() + 
//			($(window).height()-dialog_width) * 0.5});
        $(param).dialog("move", {
            top: ($(window).height() - dialog_height) * 0.5,
            left: ($(window).width() - dialog_width) * 0.5,
        });
    },

    //===================================标签、部门等公共方法=============================//	
    // 初始化下拉列表	param: 下拉列表的Id集合   url:  获取路径     type:	是部门、标签等
    initTag: function (param, url, type) {
        var page = null;
        if (type != common.isTag) {
            page = pageType;
        }
        $.request({
            url: url,
            data: {"pageType": page},
            dataType: "json",
            success: function (data) {
                $.each(param, function (index, item) {
                    var tempTag = new Array(data.rows.length);
                    for (var i = 0; i < tempTag.length; i++) {
                        tempTag[i] = data.rows[i];
                    }
                    var obj = {};

                    if (type == common.isTag) {
                        obj.state = "open";
                        obj.children = [];
                        if (item.is_search == 'Y') {
                        } else if (item.is_search == 'O') {
                            obj.id = -2;
                            obj.text = "新建";
                            tempTag.push(obj);
                        } else {
                            obj.id = -3;
                            obj.text = "请选择";
                            tempTag.unshift(obj);
                        }
                    } else {
                        if (item.is_search == 'Y') {
                            obj.id = -1;
                            obj.name = "全部";
                            tempTag.unshift(obj);
                        } else if (item.is_search == 'O') {
                            // 过滤新建 只有组织用户有新建部门、角色权限， 外协用户没有新建部门、角色权限
                            if (userType == 0) {
                                obj.id = -2;
                                obj.name = "新建";
                                tempTag.push(obj);
                            }
                        } else {
                            obj.id = -3;
                            obj.name = "请选择";
                            tempTag.unshift(obj);
                        }
                    }

                    // 表示标签树
                    if (type == common.isTag) {
                        $(item.id).combotree({
                            data: tempTag,
                        });
                    } else { // 部门等下拉列表
                        $(item.id).combobox({
                            data: tempTag,
                            valueField: 'id',
                            textField: 'name',
                            onSelect: function (param) {
                                // 新建
                                if (param.id == -2) {
                                    if (type == common.isTag) {
                                        $('.tagdialog_new').dialog('open').dialog('setTitle', '添加标签');
                                    } else if (type == common.isDept) {
                                        $('.deptdialog_new').dialog('open').dialog('setTitle', '添加部门');
                                    } else if (type == common.isRole) {
                                        $('.roledialog_new').dialog('open').dialog('setTitle', '添加角色');
                                    }
                                    // 取消选择此项
                                    $(item.id).combobox('unselect', param.id);
                                }
                            },
                            onLoadSuccess: function () {
                                // 默认选中第一项
                                if (item.is_search != 'O') {
                                    $(item.id).combobox('select', tempTag[0].id);
                                }
                            }

                        });
                    }

                });
            }
        });
    },

    // 保存快捷新建部门、标签等信息  url: 保存路径
    saveAllNew: function (url, form_id, dialog_id, reload_id, reaload_url,
                          reaload_type) {
        if ($(form_id).form('validate') != true) {
            return;
        }
        $.request({
            url: url,
            dataType: "json",
            data: $(form_id).serialize(),
            type: "post",
            success: function (result) {
                if (result.msg != 'ok') {
                    $.messager.alert('通知', '保存失败！');
                } else {
                    $.messager.alert('通知', '保存成功！');
                    // 关闭dialog
                    $(dialog_id).dialog('close');
                    // 重新加载下拉列表
                    common.initTag(reload_id, reaload_url, reaload_type);
                }

            },
        });

    },

    // 检查系统是否已经开通业务
    checkIsOpenBusiness: function () {
        var isOpen = true;
        $.request({
            url: location.path + "configurationAction!queryConfiguration.action",
            data: {"configuration.configKey": "business_is_open"},
            type: "post",
            async: false,
            success: function (result) {
                // 去掉引号
                result = result.replace(/"/gm, '');
                if (result != "yes") {
                    isOpen = false;
                }
            }
        });
        return isOpen;
    },

    /**
     * 过滤特殊字符
     * @param s
     * @returns {String}
     */
    stripscript: function (s) {
        var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]");
        var rs = "";
        for (var i = 0; i < s.length; i++) {
            rs = rs + s.substr(i, 1).replace(pattern, '');
        }
        return rs;
    },

    /**
     * 新建标签选择界面
     */
    initChoseTags: function () {
        common.totalTags = [];
        $('body').append('<div id="choseTags"></div>');
        $('body').append('<div id="choseTags_buttons"></div>');
        var choseTags = $(common.tagId);
        choseTags.css('padding', '10px');
        $('#choseTags_buttons').append("<a id='submitTags' href='javascript:void(0)' onclick=''>确定</a>");
        $('#choseTags_buttons').append("<a href='javascript:void(0)' onclick='common.closeChoseTags()'>取消</a>");
        $('#choseTags_buttons a').first().linkbutton({
            iconCls: 'icon-ok'
        });
        $('#choseTags_buttons a').last().linkbutton({
            iconCls: 'icon-cancel'
        });

        choseTags.append('<div id="showTagsChoice"></div>');
        choseTags.append('<div id="showTags"></div>');
        $('#showTagsChoice').append('<h4>已选标签：</h4>').append('<table id="show_tags_dg"></table>').css({
            'width': '100%',
            'height': '50%'
        });
        $('#showTagsChoice').append('<button id="addTagButton" style="border-radius:5px;margin-top:30px; border:1px #CCC solid;width:100px;height:30px;">添加标签</button>');
        $('#addTagButton').attr("onclick", "$('#showTags').show()");
        $('#showTagsChoice ul').css({'width': '90%', 'height': '40%'});

        if ($(common.tagInputId + "tags_ids").length == 0) {
            $(common.tagInputId).after("<input type='hidden' id='" + common.tagInputId.split('#')[1] + "tags_ids' />");
        }

        $('#showTags').css({'width': '100%', 'height': '45%'}).hide().append('<ul id="showTagsUl"></ul>');
        choseTags.dialog({
            title: "选择标签",
            width: 500,
            height: 500,
            closed: true,
            cache: false,
            modal: true,
            buttons: '#choseTags_buttons',
            draggable: false,
            onClose: function () {
                //$('#submitTags').attr('onclick','common.setTagsToInput()');
                common.myTags = [];
                common.userTags = [];
                $(common.tagId).empty();
                $(common.tagId).remove();
                $('#show_tags_dg').datagrid('loadData', []);
                common.isInitChooseTag = false;
                common.tagIds = '';
            }
        });
        $(common.tags_dg).datagrid({
            columns: [[
                {field: 'id', hidden: true, width: 80},
                {field: 'name', title: '标签名称', width: 80},
                {field: 'operate', title: '操作', align: 'center', width: 80}
            ]],
            fitColumns: true,
            rownumbers: true,
            height: 110
        });
        $.request({
            url: location.path + "tagAction!queryAll.action",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                var rows = data.rows;
                $.each(rows, function (index, item) {
                    var tag = {'id': item.id, 'name': item.text};
                    common.totalTags.push(tag);
                    $(common.tagListUl).append("<li id='" + item.id + "'><a href='javascript:void(0)'><span>" + item.text + "</span></a></li>");
                    $('#' + item.id + ">a").attr('onclick', "common.setTagToDg('" + item.id + "','" + item.text + "')");
                    if (item.children.length > 0) {
                        common.setChildrenTags(item.id, item.children);
                    }
                });
            }
        });
        common.dialog_center_show(common.tagId);
    },

    /**
     * 设置子标签
     */
    setChildrenTags: function (pLiId, tagList) {
        $("#" + pLiId + ">a").after("<div class='subs'><div class='col'><ul></ul></div><div>");
        $.each(tagList, function (index, item) {
            var tag = {'id': item.id, 'name': item.text};
            common.totalTags.push(tag);
            var liId = null;
            liId = pLiId + "-" + item.id;
            $("#" + pLiId + ">.subs>.col>ul").append("<li id='" + liId + "'><a href='javascript:void(0)'><span>" + item.text + "</span></a></li>");
            $('#' + liId + ">a").attr('onclick', "common.setTagToDg('" + liId + "','" + item.text + "')");
            if (item.children.length > 0) {
                common.setChildrenTags(liId, item.children);
            }
        });
    },


    /**
     * 打开选择标签列表(初始化)
     */
    openChooseTags: function (id) {

        //初始化标签选择数据
        common.userTags = [];

        $(common.tags_dg).datagrid('loadData', []);
        common.tagInputId = id;

        //判断标签选择框是否已经存在，不存在则新建标签选择框
        if (common.isInitChooseTag == false) {
            common.initChoseTags();
            common.isInitChooseTag = true;
        }

        //判断是否已经存在标签数据，如果有则直接加载已存在数据
        if (common.myTags.length > 0) {

            //初始化标签ids页面存储
            var tagsId = '';
            $.each(common.myTags, function (index, item) {
                if (tagsId == '') {
                    tagsId += item.id;
                } else {
                    tagsId += "," + item.id;
                }
            });
            $('' + common.tagInputId + 'tags_ids').val(tagsId.trim());

            //加载数据到已选表格
            $(common.tags_dg).datagrid('loadData', common.myTags);
        } else {

            //判断是否选择了标签
            if ($('' + common.tagInputId + 'tags_ids').val() != null && $(common.tagInputId).val() != null && $('' + common.tagInputId + 'tags_ids').val().trim() != '' && $('' + common.tagInputId + 'tags_ids').val().trim().length > 0 && $(common.tagInputId).val().trim() != '' && $(common.tagInputId).val().trim().length > 0) {
                var tagsIds = ($('' + common.tagInputId + 'tags_ids').val()).split(",");
                var tagsNames = ($(common.tagInputId).val()).split(",");
                var tagNodes = [];
                for (var i = 0; i < tagsIds.length; i++) {
                    var tagNode = {'id': tagsIds[i], 'name': tagsNames[i], 'operate': common.deleteTagOperate};
                    tagNodes.push(tagNode);
                }

                //加载数据到已选表格
                $(common.tags_dg).datagrid('loadData', tagNodes);
            }
        }

        $('#submitTags').attr('onclick', 'common.setTagsToInput()');
        $(common.tagList).hide();
        $(common.tagId).dialog('open').dialog('center');
    },

    /**
     * 关闭标签选择页面
     */
    closeChoseTags: function () {
        $(common.tagId).dialog('close');
    },

    /**
     * 设置标签到页面输入框
     */
    setTagsToInput: function () {

        //读取所选择标签列表
        var rows = $(common.tags_dg).datagrid('getRows');

        //循环分割id和name
        $.each(rows, function (index, item) {
            var ids = (item.id).split('-');
            var tagNodes = [];
            $.each(ids, function (index, item) {
                for (var i = 0; i < common.totalTags.length; i++) {
                    if (common.totalTags[i].id == item) {
                        tagNodes.push(common.totalTags[i]);
                    }
                }
            });
            common.userTags[index] = tagNodes;
        });
        var tags = common.userTags;
        var tagsName = '';
        var tagsId = '';
        $.each(tags, function (index, item) {
            var tagName = '';
            var tagId = '';
            $.each(item, function (index, item) {
                if (tagName == '' && tagId == '') {
                    tagId += item.id;
                    tagName += item.name;
                } else {
                    tagName += "-" + item.name;
                    tagId += "-" + item.id;
                }
            });
            if (tagsName == '' && tagsId == '') {
                tagsName += tagName;
                tagsId += tagId;
            } else {
                tagsName += "," + tagName;
                tagsId += "," + tagId;
            }
        });

        //填充id和name到页面
        $('' + common.tagInputId + 'tags_ids').val(tagsId.trim());
//		document.getElementById((common.tagInputId).split("#")[1] + 'tags_ids').value = tagsId.trim();
        $(common.tagInputId).val(tagsName.trim());

        //触发onblur事件
        $(common.tagInputId).blur();

        //关闭标签选择框
        common.closeChoseTags();
    },

    /**
     * 添加选择标签到已选表格
     */
    setTagToDg: function (id, name) {

        //判断所选标签是否已经选中，如果已经存在，不添加该标签到已选表格，并结束方法
        var rows = $(common.tags_dg).datagrid('getRows');
        if (rows.length != 0) {
            var isExist = false;
            $.each(rows, function (index, item) {
                if (id.trim() == (item.id).trim()) {
                    isExist = true;
                }
            });
            if (isExist) {
                return;
            }
        }

        var ids = id.split('-');
        var tagName = null;
        for (var i = 0; i < ids.length - 1; i++) {
            $.each(common.totalTags, function (index, item) {
                if (item.id.trim() == ids[i].trim()) {
                    if (tagName == null) {
                        tagName = item.name;
                    } else {
                        tagName += "-" + item.name;
                    }
                }
            });
        }
        if (tagName != null) {
            tagName += "-" + name;
        } else {
            tagName = name;
        }
        $(common.tags_dg).datagrid('appendRow', {
            id: id,
            name: tagName,
            operate: "<button onclick='common.deleteTag(" + id + ")'>删除</button>"
        });
    },

    /**
     * 删除所选标签
     */
    deleteTag: function () {
        $(common.tags_dg).datagrid({
            onClickRow: function (rowIndex, rowData) {
                $(common.tags_dg).datagrid('deleteRow', rowIndex);
            }
        });
//		$(common.tags_dg).datagrid('selectRecord', id);
//		$(common.tags_dg).datagrid('deleteRow', $(common.tags_dg).datagrid('getRowIndex',$(common.tags_dg).datagrid('getSelections')[0]));
    },

    /**
     * 给标签设值
     * @param id
     */
    setTagValues: function (id, values) {
        // 先添加隐藏域
        if ($(id + "tags_ids").length == 0) {
            $(id).after("<input type='hidden' id='" + id.split('#')[1] + "tags_ids' />");
        }

        // 给隐藏域赋值
        var names = "";
        var ids = "";
        $.each(values, function (index, item) {
            names += item.fullname + ",";
            ids += item.fullid + ",";
        });

        names = names.substring(0, names.length - 1);
        ids = ids.substring(0, ids.length - 1);
        $(id + 'tags_ids').val(ids.trim());
        $(id).val(names.trim());
    },

    /**
     * 得到所选标签，添加到集合
     */
    getTags: function (id) {
        var tagsId = '';
        var conjugate = 1;
        if (id) {
            var value = $(id + "tags_ids").val();
            if (value != null && value.trim() != '') {
                var ids = value.split(",");
                var rootId = [];
                $.each(ids, function (index, item) {
                    if (item != null && item.trim != '') {
                        var id = item.split('-');
                        $.each(id, function (index, item) {
                            if (index == id.length - 1) {
                                if (tagsId == '') {
                                    tagsId += item;
                                } else {
                                    tagsId += ',' + item;
                                }
                            }
                        });
                        rootId.push(id[0]);
                    }
                });
                if (rootId.unique().length != 1) {
                    conjugate = 0;
                }
            } else {
                tagsId = common.tagIds;
            }
        } else {
            tagsId = common.tagIds;
        }
        return {'conjugate': conjugate, 'tagIds': tagsId};
    }
});
